package com.hyg.module_report.ui.fragment;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.data.Entry;
import com.hyg.lib_base.MyView.BodyConstitutionPoint;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.DataModel.ReceiveData;
import com.hyg.lib_common.DataModel.report.HealthDetailData;
import com.hyg.lib_common.DataModel.report.PulseData;
import com.hyg.lib_common.DataModel.report.PulseDataDetail;
import com.hyg.lib_common.DataModel.report.ReportSummaryData;
import com.hyg.lib_common.DataModel.report.TongueAndFaceData;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.module_report.R;
import com.hyg.module_report.adapter.HealthReportDetailAdapter;
import com.hyg.module_report.model.HealthReportDetailData;
import com.hyg.module_report.model.PulseDatas;
import com.hyg.module_report.ui.activity.HealthReportActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;

/**
 * 报告详情
 * create an instance of this fragment.
 */
public class ReportDetailFragment extends Fragment {
    private HealthReportDetailAdapter healthReportDetailAdapter;
    private RecyclerView RV_report_detail;
    private ArrayList<HealthReportDetailData> healthReportDetailDataArrayList = new ArrayList<>();
    private HealthReportDetailData HRDD_qushi;
    private HealthReportDetailData HRDD_summary;
    private HealthReportDetailData HRDD_tongue;
    private HealthReportDetailData HRDD_pulse;
    private HealthReportDetailData HRDD_tizhi;
    private ArrayList<PulseDatas> pulseDatas = new ArrayList<>();
    HealthReportActivity Activity;

    public ReportDetailFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_repor_detail, container, false);
        RV_report_detail = view.findViewById(R.id.RV_report_detail);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Activity = (HealthReportActivity) getActivity();
        init_report_detail();
        getReportDetailData();
    }

    /**
     * description: 体检报告显示
     *
     * @author visitant
     * @time 2020/12/10 9:56
     */
    public void init_report_detail() {
        healthReportDetailAdapter = new HealthReportDetailAdapter((HealthReportActivity) getActivity(), healthReportDetailDataArrayList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        RV_report_detail.setLayoutManager(layoutManager);
        RV_report_detail.setItemAnimator(new DefaultItemAnimator());
//        RV_report_detail.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        RV_report_detail.setAdapter(healthReportDetailAdapter);
    }


    public void setRV_report_detail() {
        healthReportDetailDataArrayList.clear();
        if (!Utils.isEmpty(HRDD_qushi)) healthReportDetailDataArrayList.add(HRDD_qushi);
        if (!Utils.isEmpty(HRDD_summary)) healthReportDetailDataArrayList.add(HRDD_summary);
        if (!Utils.isEmpty(HRDD_tongue)) healthReportDetailDataArrayList.add(HRDD_tongue);
        if (!Utils.isEmpty(HRDD_pulse)) healthReportDetailDataArrayList.add(HRDD_pulse);
        if (!Utils.isEmpty(HRDD_tizhi)) healthReportDetailDataArrayList.add(HRDD_tizhi);
        healthReportDetailAdapter.notifyDataSetChanged();
    }


    public void getHealthData(String id) {
        {
            String str_tag = "2";
            FormBody formBody = new FormBody.Builder()
                    .add("reportId", id)//设置参数名称和参数值
                    .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                    .build();
            Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getHealthDataAddr);
        }
    }

    public void getCollectDetailData(String id) {
        String str_tag = "3";
        FormBody formBody = new FormBody.Builder()
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .add("reportId", id)
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getCollectDetailAddr);
    }

    public void getTongue(String id) {
        {
            String str_tag = "4";
            FormBody formBody = new FormBody.Builder()
                    .add("reportId", id)//设置参数名称和参数值
                    .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                    .build();
            Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getTongueAddr);
        }
    }

    public void getPulse(String id) {
        {
            String str_tag = "5";
            FormBody formBody = new FormBody.Builder()
                    .add("reportId", id)//设置参数名称和参数值
                    .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                    .build();
            Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getPulseAddr);
        }
    }

    public void getTiZhi(String id) {
        String str_tag = "6";
        FormBody formBody = new FormBody.Builder()
                .add("reportId", id)//设置参数名称和参数值
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getBodyAddr);
    }

    /**
     * description: 查询报告和建议 详细信息
     *
     * @author visitant
     * @time 2020/12/10 10:19
     */
    public void getReportDetailData() {
        getHealthData(Activity.MedicalId);
//      getCollectDetailData(MedicalId);
        getTongue(Activity.MedicalId);
        getPulse(Activity.MedicalId);
        getTiZhi(Activity.MedicalId);
    }

    /**
     * description: 显示健康信息
     *
     * @author visitant
     * @time 2020/12/10 10:51
     */
    public void showHealthData(ReceiveData receiveData) {
        HealthDetailData data = JSONObject.parseObject(receiveData.getData(), HealthDetailData.class);
        if (data == null) return;
        List<BodyConstitutionPoint> HealthSystemPoints = new ArrayList<>();
        String HealthSex = TextUtils.isEmpty(data.getGender()) ? "男" : data.getGender();
        HealthSystemPoints.add(new BodyConstitutionPoint("神经系统", data.getShenjingSystem()));
        HealthSystemPoints.add(new BodyConstitutionPoint("免疫系统", data.getMianyiSystem()));
        HealthSystemPoints.add(new BodyConstitutionPoint("内分泌系统", data.getNeifenmiSystem()));
        HealthSystemPoints.add(new BodyConstitutionPoint("生殖系统", data.getShengzhiSystem()));
        HealthSystemPoints.add(new BodyConstitutionPoint("循环系统", data.getXunhuanSystem()));
        HealthSystemPoints.add(new BodyConstitutionPoint("运动系统", data.getYundongSystem()));
        HealthSystemPoints.add(new BodyConstitutionPoint("呼吸系统", data.getHuxiSystem()));
        HealthSystemPoints.add(new BodyConstitutionPoint("泌尿系统", data.getMiniaoSystem()));
        HealthSystemPoints.add(new BodyConstitutionPoint("消化系统", data.getXiaohuaSystem()));
        HRDD_qushi = new HealthReportDetailData("0", HealthSystemPoints, HealthSex);
        setRV_report_detail();
    }

    /**
     * description:  显示望诊结果
     *
     * @author visitant
     * @time 2020/12/10 14:19
     */
    public void showTongueFaceData(ReceiveData receiveData) {
        TongueAndFaceData data = JSONObject.parseObject(receiveData.getData(), TongueAndFaceData.class);
        if (data.getId() == 0) return;
        HRDD_tongue = new HealthReportDetailData("2",
                data.getTongueImagePath(),
                data.getTongueVesselImagePath(),
                data.getFaceImagePath(),
                data.getTongueSpirit(),
                data.getTongueState(),
                data.getTongueColorType(),
                data.getTongueShape(),
                data.getTongueCoatColorType(),
                data.getTongueCoatType(),
                data.getTongueMailuo(),
                data.getDoctorDiagnosis(),
                data.getFaceColor(),
                data.getRenZhongColor(),
                data.getRenZhongXingTai(),
                data.getFaceDiagnosis());
        setRV_report_detail();
    }

    /**
     * description: 显示脉诊结果
     *
     * @author visitant
     * @time 2020/12/10 14:28
     */
    public void showPulseData(ReceiveData receiveData) {
        PulseData data = JSONObject.parseObject(receiveData.getData(), PulseData.class);
        for (int i = 0; i < data.getPulseDatas().size(); i++) {
            PulseDataDetail dataDetail = data.getPulseDatas().get(i);
            ArrayList<Entry> Arraydatas0 = new ArrayList<Entry>();
            ArrayList<Entry> Arraydatas1 = new ArrayList<Entry>();
            ArrayList<Entry> Arraydatas2 = new ArrayList<Entry>();
            if (!TextUtils.isEmpty(dataDetail.getData0())) {
                String[] datas0 = dataDetail.getData0().split(",");
                for (int k = 0; k < datas0.length; k++) {
                    Arraydatas0.add(new Entry(k, Integer.parseInt(datas0[k])));
                }
            }
            if (!TextUtils.isEmpty(dataDetail.getData1())) {
                String[] datas0 = dataDetail.getData1().split(",");
                for (int k = 0; k < datas0.length; k++) {
                    Arraydatas1.add(new Entry(k, Integer.parseInt(datas0[k])));
                }
            }
            if (!TextUtils.isEmpty(dataDetail.getData2())) {
                String[] datas0 = dataDetail.getData2().split(",");
                for (int k = 0; k < datas0.length; k++) {
                    Arraydatas2.add(new Entry(k, Integer.parseInt(datas0[k])));
                }
            }
            PulseDatas item = new PulseDatas(
                    dataDetail.getId() + "",
                    dataDetail.getPulseId() + "",
                    dataDetail.getPulseHand(),
                    dataDetail.getPulsePos(),
                    dataDetail.getPulsePressureType(),
                    Arraydatas0, Arraydatas1, Arraydatas2,
                    dataDetail.getStartIndex() + "",
                    dataDetail.getEndIndex() + "",
                    dataDetail.getFluency(),
                    dataDetail.getTensionDegree(),
                    dataDetail.getPulseForce(),
                    dataDetail.getPulseRate(),
                    dataDetail.getPulseType(),
                    dataDetail.getDiagnosisDate(),
                    dataDetail.getPfu(),
                    dataDetail.getSru(),
                    dataDetail.getCreateTime(),
                    dataDetail.getUpdateTime());
            pulseDatas.add(item);
        }
        String zuoshou = "", youshou = "";
        if (Utils.isEmpty(data.getLeftType())) {
            zuoshou += "未测";
        } else {
            zuoshou += data.getLeftType().substring(0, 1) + "脉";
        }
        if (Utils.isEmpty(data.getRightType())) {
            youshou += "未测";
        } else {
            youshou += data.getRightType().substring(0, 1) + "脉";
        }
        HRDD_pulse = new HealthReportDetailData("3", pulseDatas, data.getPulseZhenduan(), zuoshou, youshou);
        setRV_report_detail();
    }


    public void showPhysiqueData(ReceiveData receiveData) {
        if (!TextUtils.isEmpty(receiveData.getData())) {
            HRDD_tizhi = new HealthReportDetailData("4", receiveData.getData());
            setRV_report_detail();
        }
    }

    private MyHandler myHandler = new MyHandler(getActivity());

    private class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private HealthReportActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (HealthReportActivity) reference.get();
        }

        public void handleMessage(Message msg) {
            ReceiveData receiveData = JSONObject.parseObject(msg.obj.toString(), ReceiveData.class);
            if (receiveData == null) return;
            if (!receiveData.getCode().equals("200")) {
                activity.ErrorDialog(receiveData.getMessage());
                return;
            }
            switch (msg.what) {
                case 1://查询报告id，是否有此报告
                    getReportDetailData();
                    break;
                case 2: //解析健康信息并显示
                    showHealthData(receiveData);
                    break;
                case 3: //查询结果汇总（目前使用what= 4 5 6 代替）
                    ReportSummaryData summaryData = JSONObject.parseObject(receiveData.getData(), ReportSummaryData.class);
//                    activity.HRDD_summary = new HealthReportDetailData("1", shetufenxi + miantufenxi);
                    break;
                case 4:// 查询望诊评估
                    showTongueFaceData(receiveData);
                    break;
                case 5://查询脉诊评估
                    showPulseData(receiveData);
                    break;
                case 6://查询体质评估
                    showPhysiqueData(receiveData);
                    break;
//                case 7://查询耳电评估
//                    //                    try {
//                    //                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
//                    //                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
//                    //                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                    //                        Log.d("welcomeadLogin", jsondata + "");
//                    //                        if (status.equals("200")) {
//                    //                            if (null != jsondata.getString("data") && !jsondata.getString("data").equals("")) {
//                    //                                //                                JSONObject data = new JSONObject(URLDecoder.decode(jsondata.getString("data"), "utf-8"));
//                    //                                JSONObject data = new JSONObject(jsondata.getString("data"));
//                    //                                //实例化常量值
//                    //                                db.beginTransaction();
//                    //                                ContentValues cValue = new ContentValues();
//                    //                                //调用insert()方法插入数据
//                    //                                cValue.put("EarId", data.getString("id").equals("null") ? "" : data.getString("id"));
//                    //                                cValue.put("doctorId", data.getString("doctorId").equals("null") ? "" : data.getString("doctorId"));
//                    //                                cValue.put("medicalID", data.getString("medicalID").equals("null") ? "" : data.getString("medicalID"));
//                    //                                cValue.put("basicImpedance", data.getString("basicImpedance").equals("null") ? "" : data.getString("basicImpedance"));
//                    //                                cValue.put("acuPointImpedance", data.getString("acuPointImpedance").equals("null") ? "" : data.getString("acuPointImpedance"));
//                    //                                cValue.put("diagnosisPath", data.getString("diagnosisPath").equals("null") ? "" : data.getString("diagnosisPath"));
//                    //                                cValue.put("reMarks", data.getString("reMarks").equals("null") ? "" : data.getString("reMarks"));
//                    //                                cValue.put("diagnosisDate", data.getString("diagnosisDate").equals("null") ? "" : data.getString("diagnosisDate"));
//                    //                                cValue.put("createTime", data.getString("createTime").equals("null") ? "" : data.getString("createTime"));
//                    //                                cValue.put("updateTime", data.getString("updateTime").equals("null") ? "" : data.getString("updateTime"));
//                    //
//                    //                                db.replace("EarData", null, cValue);//根据主键id判断，有就替换，没有就插入
//                    //                                db.setTransactionSuccessful();
//                    //                                db.endTransaction();
//                    //
//                    //                                queryErXueDB(data.getString("id"));
//                    //                            }
//                    //                        } else {
//                    //                            ErrorDialog(message);
//                    //                        }
//                    //                    } catch (JSONException e) {
//                    //                        Log.d(CrashTAG,""+e.getMessage());
//                    //                    } catch (UnsupportedEncodingException e) {
//                    //                        Log.d(CrashTAG,""+e.getMessage());
//                    //                    }
//                    //                    break;
//                case 8://查询大数据评估
//                    //                    try {
//                    //                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
//                    //                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
//                    //                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                    //                        //                        Log.d("welcomeDashuju", jsondata + "");
//                    //                        if (status.equals("200")) {
//                    //                            if (null != jsondata.getString("data") && !jsondata.getString("data").equals("")) {
//                    //                                JSONObject data = new JSONObject(jsondata.getString("data"));
//                    //                                if (!data.getString("title").equals("null") && !data.getString("title").equals("")) {
//                    //                                    activity.Name = data.getString("title");
//                    //                                }
//                    //                                if (!data.getString("habitus").equals("") && !data.getString("habitus").equals("null")) {
//                    //                                    //                                    PhysiqueType = data.getString("habitus");
//                    //                                    //                                    String[] strList = data.getString("habitus").split(",");
//                    //                                    activity.DashujuPhysiqueType = activity.setPointsTitle(activity.newGetPoint(data.getString("habitus")));
//                    //                                }
//                    //                                activity.load_dashuju = true;
//                    //                            }
//                    //                        } else {
//                    //                            activity.ErrorDialog(message);
//                    //                        }
//                    //                    } catch (JSONException e) {
//                    //                        Log.d(CrashTAG,""+e.getMessage());
//                    //                    } catch (UnsupportedEncodingException e) {
//                    //                        Log.d(CrashTAG,""+e.getMessage());
//                    //                    }
//                    //                    activity.setInit();
//                    break;
                case 101:
                    if (activity.pDialog.isShowing()) {
                        activity.pDialog.dismiss();
                    }
                    break;
            }
        }
    }

    public static void e(String TAG, String msg) {
        int strLength = msg.length();
        int start = 0;
        int end = 2000;
        for (int i = 0; i < 100; i++) {
            //剩下的文本还是大于规定长度则继续重复截取并输出
            if (strLength > end) {
                Log.e(TAG + i, msg.substring(start, end));
                start = end;
                end = end + 2000;
            } else {
                Log.e(TAG, msg.substring(start, strLength));
                break;
            }
        }
    }

}